#include "button_hal.h"

static flex_button_t user_button[USER_BUTTON_MAX] = { 0 };

static uint8_t common_btn_read(void* arg)
{
  uint8_t value = 0;

  flex_button_t* btn = (flex_button_t*)arg;

  switch(btn->id)
  {
  case USER_BUTTON_0:
    value = gpio_input_data_bit_read(GPIOA, GPIO_PINS_3);
    break;
  case USER_BUTTON_1:
    value = gpio_input_data_bit_read(GPIOA, GPIO_PINS_4);
    break;
  case USER_BUTTON_2:
    value = gpio_input_data_bit_read(GPIOB, GPIO_PINS_0);
    break;
  case USER_BUTTON_3:
    value = gpio_input_data_bit_read(GPIOB, GPIO_PINS_11);
    break;
  default:
    break;
  }

  return value;
}

static void common_btn_evt_cb(void* arg)
{
  flex_button_t* btn = (flex_button_t*)arg;

//  printf("id: [%d]  event: [%d]  repeat: %d\r\n",
//         btn->id,
//         btn->event,
//         btn->click_cnt);

  // left
  if(btn->id == 1 && btn->event == FLEX_BTN_PRESS_CLICK)
  {
    menu_up();
  }
  // right
  if(btn->id == 0 && btn->event == FLEX_BTN_PRESS_CLICK)
  {
    menu_down();
  }
  if(btn->id == 1 && btn->event == FLEX_BTN_PRESS_DOUBLE_CLICK)
  {
    menu_back();
  }
  if(btn->id == 0 && btn->event == FLEX_BTN_PRESS_DOUBLE_CLICK)
  {
    menu_go();
  }
}

void TMR6_DAC_GLOBAL_IRQHandler(void)
{
  if(tmr_flag_get(TMR6, TMR_OVF_FLAG) == SET)
  {
    flex_button_scan();
    tmr_flag_clear(TMR6, TMR_OVF_FLAG);
  }
}

void user_button_init(void)
{
  gpio_init_type gpio_initstruct;
  gpio_default_para_init(&gpio_initstruct);
  crm_periph_clock_enable(CRM_GPIOA_PERIPH_CLOCK, TRUE);
  crm_periph_clock_enable(CRM_GPIOB_PERIPH_CLOCK, TRUE);
  gpio_initstruct.gpio_drive_strength = GPIO_DRIVE_STRENGTH_STRONGER;
  gpio_initstruct.gpio_mode = GPIO_MODE_INPUT;
  gpio_initstruct.gpio_out_type = GPIO_OUTPUT_PUSH_PULL;
  gpio_initstruct.gpio_pins = GPIO_PINS_3 | GPIO_PINS_4;
  gpio_initstruct.gpio_pull = GPIO_PULL_UP;
  gpio_init(GPIOA, &gpio_initstruct);
  gpio_initstruct.gpio_pins = GPIO_PINS_0 | GPIO_PINS_11;
  gpio_init(GPIOB, &gpio_initstruct);

  /* enable tmr1 clock */
  crm_periph_clock_enable(CRM_TMR6_PERIPH_CLOCK, TRUE);

  /* tmr1 configuration */
  /* time base configuration */
  tmr_base_init(TMR6, 199, (288000000 / 10000) - 1);
  tmr_cnt_dir_set(TMR6, TMR_COUNT_UP);
  /* overflow interrupt enable */
  tmr_interrupt_enable(TMR6, TMR_OVF_INT, TRUE);
  nvic_irq_enable(TMR6_DAC_GLOBAL_IRQn, 1, 0);
  tmr_counter_enable(TMR6, TRUE);

  for(uint8_t i = 0; i < USER_BUTTON_MAX; i ++)
  {
    user_button[i].id = i;
    user_button[i].usr_button_read = common_btn_read;
    user_button[i].cb = common_btn_evt_cb;
    user_button[i].pressed_logic_level = 0;
    user_button[i].short_press_start_tick = FLEX_MS_TO_SCAN_CNT(800);
    user_button[i].long_press_start_tick = FLEX_MS_TO_SCAN_CNT(3000);
    user_button[i].long_hold_start_tick = FLEX_MS_TO_SCAN_CNT(4500);

    flex_button_register(&user_button[i]);
  }
}